<?php

class ArtistsController extends Controller
{
	public function actionIndex()
	{
		$model=new Artists('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Artists']))
			$model->attributes=$_GET['Artists'];

		$this->render('index',array(
			'model'=>$model,
		));
	}

	public function actionCreate(){
		$model = new Artists('create');
		$profile = new ArtistProfile;
		$social = new ArtistSocial;
        $seotool = new SeoTools;
		if (isset($_POST['Artists'],$_POST['ArtistProfile'],$_POST['ArtistSocial'])) {
			$model->attributes = $_POST['Artists'];
            $model->url = $this->createSlug($model->nickname);
            $model->createddate = date("Y-m-d H:i:s");
		    $model->dateofbirth = date("Y-m-d", strtotime($_POST['Artists']['dateofbirth']));
			$profile->attributes = $_POST['ArtistProfile']; 

			if(CUploadedFile::getInstance($model,'image') != null && CUploadedFile::getInstance($model,'imagecover') != null){
                // Save image here
                $imagePath = IMAGES_DIR . 'artists/' . date('Ymd', strtotime($model->createddate)) . '/';
                if ($model->nickname !== '') {
                    $imageUploadFile = CUploadedFile::getInstance($model, 'image');
                    if ($imageUploadFile !== null) {
                        $model->image = $model->url . '.' . $imageUploadFile->extensionName;
                        if (!file_exists($imagePath)) {
                            mkdir($imagePath, 0777, true);
                        }
                        $imageUploadFile->saveAs($imagePath . $model->image);
                        // Resize images
                        $this->resizeNormalImage($imagePath, $model->image, $model->createddate);
                    }
                    else {
                        if (isset($_POST['Events']['currentImage'])) {
                            $image = $_POST['Events']['currentImage'];
                            $model->image = $model->url . '.' . pathinfo($image, PATHINFO_EXTENSION);
                            copy($imagePath . $image, $imagePath . $model->image);
                            // Resize images
                            $this->resizeNormalImage($imagePath, $model->image, $model->createddate);
                        }
                    }
                    
                    $imageUploadFile = CUploadedFile::getInstance($model, 'imagecover');
                    if ($imageUploadFile !== null) {
                        $model->imagecover = $model->url . '_cover.' . $imageUploadFile->extensionName;
                        $imageUploadFile->saveAs($imagePath . $model->imagecover);
                        // Resize images
                        $this->resizeNormalImage($imagePath, $model->imagecover, $model->createddate);
                    }
                    else {
                        if (isset($_POST['Events']['currentImage'])) {
                            $image = $_POST['Events']['currentImage'];
                            $model->imagecover = $model->url . '.' . pathinfo($image, PATHINFO_EXTENSION);
                            copy($imagePath . $image, $imagePath . $model->imagecover);
                            // Resize images
                            $this->resizeNormalImage($imagePath, $model->imagecover, $model->createddate);
                        }
                    }
                }
		        
		        if($model->validate()){ 
		        	$model->save();
                    $seotool->attributes = $_POST['SeoTools'];
                    $seotool->metarobot = '';
                    $seotool->tables = 'artists';
                    $seotool->table_id = $model->id;
                    $seotool->status = 'A';
                    $seotool->posteddate = date('Y-m-d H:i:s');
                    $seotool->save();
					$profile->artist_id = $model->id;
					$profile->description = $_POST['ArtistProfile']['description'];
					$profile->save(); 

					foreach($_POST['ArtistSocial']['social_id'] as $k=>$data)
                    {
		                    $addsocial = new ArtistSocial;  
		                    $addsocial->social_id = $_POST["ArtistSocial"]['social_id'][$k];
		                    $addsocial->url = $_POST["ArtistSocial"]['url'][$k];
		                    $addsocial->artist_id = $model->id;
		                    $addsocial->save() ;
                	}
					$this->redirect(array('view','slug'=>$model->url));
				}
			}
		}
		$this->render('create',array(
			'model'=>$model,
            'profile'=>$profile,
            'social'=>$social,
            'seotool'=>$seotool
		));
	}

	public function actionUpdate($slug)
	{
		$model = Artists::model()->findByAttributes(array('url'=>$slug));
        $model->scenario = 'update';
        $social = new ArtistSocial ;
		if (isset($_POST['Artists'], $_POST['ArtistProfile'])) {
			$model->attributes = $_POST['Artists'];
            $model->url = $this->createSlug($model->nickname);
		    $model->dateofbirth = date("Y-m-d", strtotime($_POST['Artists']['dateofbirth']));
			$model->profile->attributes = $_POST['ArtistProfile']; 

			if(CUploadedFile::getInstance($model,'image') != null || CUploadedFile::getInstance($model,'imagecover') != null){
                // Save image here
                $imagePath = IMAGES_DIR . 'artists/' . date('Ymd', strtotime($model->createddate)) . '/';
                if ($model->nickname !== '') {
                    $imageUploadFile = CUploadedFile::getInstance($model, 'image');
                    if ($imageUploadFile !== null) {
                        $model->image = $model->url . '.' . $imageUploadFile->extensionName;
                        if (!file_exists($imagePath)) {
                            mkdir($imagePath, 0777, true);
                        }
                        $imageUploadFile->saveAs($imagePath . $model->image);
                        // Resize images
                        $this->resizeNormalImage($imagePath, $model->image, $model->createddate);
                    }
                    else {
                        if (isset($_POST['Events']['currentImage'])) {
                            $image = $_POST['Events']['currentImage'];
                            $model->image = $model->url . '.' . pathinfo($image, PATHINFO_EXTENSION);
                            copy($imagePath . $image, $imagePath . $model->image);
                            // Resize images
                            $this->resizeNormalImage($imagePath, $model->image, $model->createddate);
                        }
                    }
                    
                    $imageUploadFile = CUploadedFile::getInstance($model, 'imagecover');
                    if ($imageUploadFile !== null) {
                        $model->imagecover = $model->url . '_cover.' . $imageUploadFile->extensionName;
                        $imageUploadFile->saveAs($imagePath . $model->imagecover);
                        // Resize images
                        $this->resizeNormalImage($imagePath, $model->imagecover, $model->createddate);
                    }
                    else {
                        if (isset($_POST['Events']['currentImage'])) {
                            $image = $_POST['Events']['currentImage'];
                            $model->imagecover = $model->url . '.' . pathinfo($image, PATHINFO_EXTENSION);
                            copy($imagePath . $image, $imagePath . $model->imagecover);
                            // Resize images
                            $this->resizeNormalImage($imagePath, $model->imagecover, $model->createddate);
                        }
                    }
                }
			}
            if($model->validate()){ 
                $model->save();
                $model->seotool->attributes = $_POST['SeoTools'];
                $model->seotool->save();
                $model->profile->save(); 

                $this->redirect(array('view','slug'=>$model->url));
            }
		}
		$this->render('update',array(
			'model'=>$model,
            'social'=>$social
		));
	}

	// add image to ArtistImages
	public function actionAddImage($id){
		$model = Artists::model()->findByPk($id);
		$listImage = ArtistImages::model()->findAllByAttributes(array('artist_id'=>$id));
		$artistImages = new ArtistImages ;
		if(isset($_FILES['image']))
        {
            $images = CUploadedFile::getInstancesByName('image');
            if (isset($images) && count($images) > 0) {
                foreach ($images as $key => $pic) {
                	$fileName = 'artists_' .$pic->name. time(). '.' .$this->getExtensionName($pic->name) ;
                    if ($pic->saveAs(IMAGES_DIR.'/Artists/' .$fileName)) {
                        $artistImages = new ArtistImages() ;
                        $artistImages->image = $fileName;
                        $artistImages->artist_id = $model->id;
                        $artistImages->save(); // DONE
                    }
                    else{
                    	Yii::app()->user->setFlash('error',"<b>error.<b/>");
                    }
                }
            }
        }
		$this->render('addImage',array('model'=>$model,'image'=>$artistImages,'listImage'=>$listImage));
	}

	public function getExtensionName($name)
	{
	    if(($pos=strrpos($name,'.'))!==false)
	        return (string)substr($name,$pos+1);
	    else
	        return '';
	}

	public function actionView($slug){
		$model = Artists::model()->findByAttributes(array('url'=>$slug));
        
        if (empty($model)) {
            throw new CHttpException(404,'The requested page does not exist.');
        }
        
        $criteria = new CDbCriteria;
        $criteria->condition = 'status="A"';
        $criteria->with = array('eventArtist'=>array(
            'joinType'=>'INNER JOIN',               
            'condition'=>'eventArtist.artist_id = '.$model->id,
            'together'=>TRUE
        ));
        
        $dataProvider=new CActiveDataProvider('Events',
			array(
				'criteria'=>$criteria,
				'sort'=>array(
					'defaultOrder'=>'enddate ASC, startdate DESC',
				),
				'pagination'=>array(
					'pageSize'=>10,
					'pageVar'=>'page',
				),
			)
		);
        
        $eventArtist = new EventArtists;
        
        $this->render('view', array(
            'model'=>$model,
            'dataProvider'=>$dataProvider,
            'eventArtist'=>$eventArtist
        ));
	}

	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();
        $criteria = new CDbCriteria;
        $criteria->condition='artist_id='.$id;
        ArtistProfile::model()->deleteAll($criteria);
        ArtistSocial::model()->deleteAll($criteria);
		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
	}
    
    public function actionAddEvent($slug)
	{
		$model = new EventArtists;
		if (isset($_POST['EventArtists'])) {
			$model->attributes = $_POST['EventArtists'];
			if ($model->save()) {
				$this->redirect(array('/Events/artists/view', 'slug'=>$slug));
			}
		}
	}
	public function actionRemoveEvent($artist, $event)
	{
		$model = EventArtists::model()->findByAttributes(array('artist_id'=>$artist, 'event_id'=>$event))->delete();
		
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	public function loadModel($id)
	{
		$model= Artists::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
}